<?php


namespace app\voip\controller;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\voip\func\SmsFunc;
use app\voip\model\Sms;
use vae\controller\AdminCheckAuth;

class SmsController extends AdminCheckAuth
{
    /**
     * 短信配置页
     */
    public function index()
    {
        return view();
    }
    public function sig()
    {
        return view();
    }
    public function ajaxGetSigSms()
    {
        if (!empty(input()['keywords'])){
            SmsFunc::addSmsSig(input()['keywords']);
        }
        $result=SmsFunc::getSmsSigList([]);
        return vae_assign(0,'',$result);
    }
    public function tp()
    {
        return view();
    }
    public function ajaxDelSigSms($id)
    {
        try{
            $result=SmsFunc::delSmsSig($id);

        }catch (\Exception $e){
            return vae_assign(0,$e->getMessage());
        }
        return vae_assign();
    }

    /**
     * @param $id
     */
    public function ajaxDelSmsData($id)
    {
        try{
            SmsFunc::delSmsData($id);
        }catch (\Exception $e){
            return vae_assign(0,$e->getMessage());
        }
        return vae_assign();
    }
    public function updateSms($id)
    {
        $typeResult=SmsFunc::getTypeList();
        $where=[];
        $where['status']=1;
        $smsSig    =SmsFunc::getSmsSigList($where);
        $where=[];
        $where['status']=1;
        $smsData   =SmsFunc::getSmsDataList($where);
        $smsInfo=SmsFunc::getInfo($id);
        return view('',['typeList'=>$typeResult,'smsSig'=>$smsSig,'smsData'=>$smsData,'info'=>$smsInfo]);
    }
    public function updateSmsData()
    {
        try{
            $validate=validate('SmsAuth');
            if (!$validate->scene(__FUNCTION__)->check(input())){
                throw new \Exception($validate->getError());
            }
            $data=input();
            SmsFunc::updateSms($data);
        }catch (\Exception $e){
            return vae_assign(0,$e->getMessage());
        }
        return vae_assign();
    }

    /**
     * @param $id
     * @param $status
     * @return void
     */
    public function updateSmsStatus($id,$status)
    {
        try{
            switch ($status){
                case '正常':
                    $status=0;
                    break;
                case '禁用':
                    $status=1;
                    break;
            }
            SmsFunc::updateSms(['id'=>$id,'status'=>$status]);
        }catch (\Exception $e){
            return vae_assign(0,$e->getMessage());
        }
        return vae_assign();

    }


    public function add()
    {
        $typeResult=SmsFunc::getTypeList();
        $where=[];
        $where['status']=1;
        $smsSig    =SmsFunc::getSmsSigList($where);
        $where=[];
        $where['status']=1;
        $smsData   =SmsFunc::getSmsDataList($where);
        return view('',['typeList'=>$typeResult,'smsSig'=>$smsSig,'smsData'=>$smsData]);
    }

    public function addSms()
    {
        try{
            $validate=validate('SmsAuth');
            if (!$validate->scene(__FUNCTION__)->check(input())){
                throw new \Exception($validate->getError());
            }
            $data=input();
            $data['uniqid']='SMS'.date("Ymd").uniqid();
            SmsFunc::addInfo($data);
        }catch (\Exception $e){
            return vae_assign(0,$e->getMessage());
        }
        return vae_assign();
    }
    public function type()
    {

        return view();
    }
    public function ajaxGetSms()
    {

        if (!request()->isAjax()){return view('index');}
        $where = array();
        $param = vae_get_param();

        if(!empty($param['keywords'])) {
            $where['s1.id|s1.title|s1.intro'] = ['like', '%' . $param['keywords'] . '%'];
        }
        $rows = empty($param['limit']) ? \think\Config::get('paginate.list_rows') : $param['limit'];

        return vae_assign_table(0,'',SmsFunc::getInfoList($where,$rows,$param));

    }
    public function ajaxGetSmsData()
    {

        if (!request()->isAjax()){return view('index');}
        $where = array();
        $param = vae_get_param();
        if(!empty($param['keywords'])) {
            $where['id|name|number'] = ['like', '%' . $param['keywords'] . '%'];
        }
        $rows = empty($param['limit']) ? \think\Config::get('paginate.list_rows') : $param['limit'];
        return vae_assign_table(0,'',SmsFunc::getSmsDataInfoList($where,$rows,$param));
    }

    /**
     * @return \Swoft\Http\Message\Server\Response|\think\response\View
     */
    public function tpAdd()
    {
        return view();
    }
    public function tpAddData()
    {
        try{
            $validate=validate('SmsAuth');
            if (!$validate->scene(__FUNCTION__)->check(input())){
                throw new \Exception($validate->getError());
            }
            SmsFunc::smsDataAdd(input());
        }catch (\Exception $e){
            return vae_assign(0,$e->getMessage());
        }
        return vae_assign();
    }
    public function ajaxGetTypeSms()
    {
        if (!empty(input('keywords'))){
            $data=[];
            $data['name']=input('keywords');
            SmsFunc::addTypeList($data);
        }
        $result=SmsFunc::getTypeList();
        return vae_assign(0,'',$result);
    }

    /**
     * @param $id
     * @param $phone
     * @param int $type
     * @return bool
     * @throws \think\exception\DbException
     */
    public function sendSms($id, $phone, $type=1)
    {
        $smsInfo=SmsFunc::getInfo($id);
        $smsData=$smsInfo['data'];
        $isSmsData=$smsInfo['is_data'];
        $sendData=[];
        if ($isSmsData==1){
            $smsData=explode(',',$smsData);
            $sendData=[];
            foreach ($smsData as $val)
            {
                $res=explode('=',$val);
                $sendData[$res[0]]=$res[1];
            }
            $sendData=json_encode($sendData);
        }
        if ($type==1){
            $phone=session('callNumber');
        }
        $result=$this->sendAlSms($phone,$smsInfo['sig'],$smsInfo['code'],$sendData,$isSmsData);
        return $result;
    }
    private function sendAlSms($phone, $sig, $code, $data,$isData)
    {
        AlibabaCloud::accessKeyClient(config('ALIAccessKeyId'), config('ALIAccessKeySecret'))
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asGlobalClient();
        try {
            $sendData= [
                'RegionId' => 'cn-hangzhou',
                'PhoneNumbers' => $phone,
                'SignName' => $sig,
                'TemplateCode' => $code,
            ];
            if ($isData==1){
                $sendData['TemplateParam']=$data;
            }
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' =>$sendData,
                ])
                ->request();
            $arr=$result->toArray();


            if ($arr['Code']!='OK'){
                throw new \Exception('');
            }
            return true;
        } catch (ClientException $e) {
            return false;
        } catch (ServerException $e) {
            return false;
        }catch (\Exception $e){
            return false;
        }
    }
}